﻿@model CustomerListModel
@using Telerik.Web.Mvc.UI;
@using System.Globalization;
@{
    var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
    
    //page title
    ViewBag.Title = T("Admin.Customers.Customers").Text;
}
@using (Html.BeginForm("ExportExcelAll", "Customer", FormMethod.Post, new { id = "post-form" }))
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/subsites/Administration/Content/images/ico-customers.png")" alt="" />
            @T("Admin.Customers.Customers")
        </div>
        <div class="options">
            <a href="@Url.Action("Create")" class="t-button">@T("Admin.Common.AddNew")</a>
            <a href="@Url.Action("ExportXmlAll")" class="t-button">@T("Admin.Common.ExportToXml.All")</a>
            <input type="button" id="exportxml-selected" class="t-button" value="@T("Admin.Common.ExportToXml.Selected")" />
            <input type="button" id="exportexcel-all" class="t-button" value="@T("Admin.Common.ExportToExcel.All")" />
            <input type="button" id="exportexcel-selected" class="t-button" value="@T("Admin.Common.ExportToExcel.Selected")" />
        </div>
    </div>
    <table width="100%">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchCustomerRoleIds):
            </td>
            <td class="adminData">
                @foreach (var customerRole in Model.AvailableCustomerRoles)
                {
                    <input type="checkbox" name="SearchCustomerRoleIds" value="@customerRole.Id"
                @if (Model.SearchCustomerRoleIds != null && Model.SearchCustomerRoleIds.Contains(customerRole.Id))
                {
                    <text>checked="checked"</text>
                }
                />@customerRole.Name
                    <br />
                }
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.RegistrationFrom):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.RegistrationFrom)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.RegistrationTo):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.RegistrationTo)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.RoleSearchRestriction):
            </td>
            <td class="adminData">
                @Html.CheckBoxFor(model => model.RoleSearchRestriction)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchEmail):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchEmail)
            </td>
        </tr>
        @if (Model.UsernamesEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchUsername):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.SearchUsername)
                </td>
            </tr>
        }
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchFirstName):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchFirstName)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchLastName):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchLastName)
            </td>
        </tr>
        @if (Model.DateOfBirthEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchDayOfBirth):
                </td>
                <td class="adminData">
                    @{
            var monthOfBirthValues = new List<SelectListItem>();
            monthOfBirthValues.Add(new SelectListItem() { Text = T("Admin.Customers.Customers.List.SearchDateOfBirth.Month").Text, Value = "0" });
            for (int i = 1; i <= 12; i++)
            {
                monthOfBirthValues.Add(new SelectListItem() { Text = i.ToString(CultureInfo.InvariantCulture), Value = i.ToString(CultureInfo.InvariantCulture) });
            }
            var dayOfBirthValues = new List<SelectListItem>();
            dayOfBirthValues.Add(new SelectListItem() { Text = T("Admin.Customers.Customers.List.SearchDateOfBirth.Day").Text, Value = "0" });
            for (int i = 1; i <= 31; i++)
            {
                dayOfBirthValues.Add(new SelectListItem() { Text = i.ToString(CultureInfo.InvariantCulture), Value = i.ToString(CultureInfo.InvariantCulture) });
            }
                    }
                    @Html.DropDownListFor(model => Model.SearchMonthOfBirth, monthOfBirthValues)
                    @Html.DropDownListFor(model => Model.SearchDayOfBirth, dayOfBirthValues)
                </td>
            </tr>
        }
        
        @if (Model.CompanyEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchCompany):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.SearchCompany)
                </td>
            </tr>
        }        
        @if (Model.PhoneEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchPhone):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.SearchPhone)
                </td>
            </tr>
        }
        @if (Model.CellPhoneEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchCellPhone):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.SearchCellPhone)
                </td>
            </tr>
        }
        @if (Model.ZipPostalCodeEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchZipPostalCode):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.SearchZipPostalCode)
                </td>
            </tr>
        } 
        <tr>
            <td colspan="2">
                <input type="button" id="search-customers" class="t-button" value="@T("Admin.Common.Search")" />
            </td>
        </tr>
    </table>
    <p>
    </p>
    <table class="adminContent">
        <tr>
            <td>
                @(Html.Telerik().Grid<CustomerModel>(Model.Customers.Data)
                    .Name("customers-grid")
                    .ClientEvents(events => events
                        .OnDataBinding("onDataBinding")
                        .OnDataBound("onDataBound"))
                    .Columns(columns =>
                    {
                        columns.Bound(x => x.Id)
                        .Template(x => string.Format("<input type='checkbox' name='checkedRecords' value='{0}' class='checkboxGroups'/>", x.Id))
                        .ClientTemplate("<input type='checkbox' name='checkedRecords' value='<#= Id #>' class='checkboxGroups'/>")
                        .Title("<input id='mastercheckbox' type='checkbox'/>")
                        .Width(50)
                        .HtmlAttributes(new { style = "text-align:center" })
                        .HeaderHtmlAttributes(new { style = "text-align:center" });

                        columns.Bound(x => x.Id)
                            .Width(50);
                        //I don't know why but the customer list does not have an 'Edit' column in the grid on some machines (maybe because we are inside Html.BeginForm()).
                        //That's why the 'Email' column is clickable.
                        columns.Bound(x => x.Email)
                            .Template(x => Html.ActionLink(x.Email, "Edit", "Customer", new { id = x.Id }, new { }))
                            .ClientTemplate("<a href=\"" + @Url.Content("~/Admin/Customer/Edit/") + "<#= Id #>\"><#= Email #></a>")
                            .Width(150);
                        columns.Bound(x => x.Username)
                            .Width(150)
                            .Visible(Model.UsernamesEnabled);
                        columns.Bound(x => x.FullName)
                            .Width(200);
                        columns.Bound(x => x.CustomerRoleNames)
                            .Width(200);
                        columns.Bound(x => x.Company)
                            .Width(150)
                            .Visible(Model.CompanyEnabled);
                        columns.Bound(x => x.CellPhone)
                            .Width(100)
                            .Visible(Model.CellPhoneEnabled);
                        columns.Bound(x => x.Phone)
                            .Width(100)
                            .Visible(Model.PhoneEnabled);
                        columns.Bound(x => x.ZipPostalCode)
                            .Width(75)
                            .Visible(Model.ZipPostalCodeEnabled);
                        columns.Bound(x => x.Active)
                            .Template(
                                @<img alt="" src="@Url.Content("~/subsites/Administration/Content/images/active-" + item.Active.ToString().ToLowerInvariant() + ".gif")" />
                            )
                            .ClientTemplate("<img alt='' src='" + Url.Content("~/subsites/Administration/Content/images/") + "active-<#= Active #>.gif' />")
                            .Centered()
                            .Width(100);
                        columns.Bound(x => x.CreatedOn)
                            .Template(x => x.CreatedOnStr).ClientTemplate("<#= CreatedOnStr #>")
                            .Width(140);
                        columns.Bound(x => x.LastActivityDate)
                            .Template(x => x.LastActivityDateStr).ClientTemplate("<#= LastActivityDateStr #>")
                            .Width(140);
                        columns.Bound(x => x.Id)
                            .Width(50)
                            .Centered()
                            .Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "Edit", new { id = x.Id }))
                            .ClientTemplate("<a href=\"Edit/<#= Id #>\">" + T("Admin.Common.Edit").Text + "</a>")
                            .Title(T("Admin.Common.Edit").Text);
                    })
                                            .Pageable(settings => settings.Total(Model.Customers.Total).PageSize(gridPageSize).Position(GridPagerPosition.Both))
                                            .DataBinding(dataBinding => dataBinding.Ajax().Select("CustomerList", "Customer"))
                                            .EnableCustomBinding(true))
            </td>
        </tr>
    </table>
    
    <script type="text/javascript">

    var selectedIds = [];
    var customerRoleIds = [];
    var searchModel = [];
    $(document).ready(function () {

        //search button
        $('#search-customers').click(function () {
            var grid = $('#customers-grid').data('tGrid');
            grid.currentPage = 1; //new search. Set page size to 1
            grid.ajaxRequest();
            return false;
        });

        $("#@Html.FieldIdFor(model => model.RegistrationFrom)").keydown(function (event) {
            if (event.keyCode == 13) {
                $("#search-customers").click();
                return false;
            }
        });

        $("#@Html.FieldIdFor(model => model.RegistrationTo)").keydown(function (event) {
            if (event.keyCode == 13) {
                $("#search-customers").click();
                return false;
            }
        });

        $("#@Html.FieldIdFor(model => model.SearchEmail)").keydown(function (event) {
            if (event.keyCode == 13) {
                $("#search-customers").click();
                return false;
            }
        });
        $("#@Html.FieldIdFor(model => model.SearchUsername)").keydown(function (event) {
            if (event.keyCode == 13) {
                $("#search-customers").click();
                return false;
            }
        });
        $("#@Html.FieldIdFor(model => model.SearchFirstName)").keydown(function (event) {
            if (event.keyCode == 13) {
                $("#search-customers").click();
                return false;
            }
        });
        $("#@Html.FieldIdFor(model => model.SearchLastName)").keydown(function (event) {
            if (event.keyCode == 13) {
                $("#search-customers").click();
                return false;
            }
        });
        $("#@Html.FieldIdFor(model => model.SearchCompany)").keydown(function (event) {
            if (event.keyCode == 13) {
                $("#search-customers").click();
                return false;
            }
        });
        $("#@Html.FieldIdFor(model => model.SearchPhone)").keydown(function (event) {
            if (event.keyCode == 13) {
                $("#search-customers").click();
                return false;
            }
        });
        $("#@Html.FieldIdFor(model => model.SearchZipPostalCode)").keydown(function (event) {
            if (event.keyCode == 13) {
                $("#search-customers").click();
                return false;
            }
        });


        //"Export Excel selected" button
        $('#exportexcel-selected').click(function (e) {
            e.preventDefault();
            //redirect to required URL
            setLocation('@(Url.Action("ExportExcelSelected", "Customer"))?selectedIds=' + selectedIds.join(","));
            return false;
        });

        //"Export Excel all" button
        $('#exportexcel-all').click(function (e) {
            e.preventDefault();
            //redirect to required URL

            var grid = $('#customers-grid').data('tGrid');
            grid.currentPage = 1; //new search. Set page size to 1
            grid.ajaxRequest();
            getValuesFromControls();
            $('#post-form').submit();
            return false;
        });
  
        //"Export XML selected" button
        $('#exportxml-selected').click(function (e) {
            e.preventDefault();
            //redirect to required URL
            setLocation('@(Url.Action("ExportXmlSelected", "Customer"))?selectedIds=' + selectedIds.join(","));
            return false;
        });

        $('#mastercheckbox').click(function () {
            $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
        });

        //wire up checkboxes.
        $('#customers-grid input[type=checkbox][id!=mastercheckbox]').live('change', function (e) {
            var $check = $(this);
            if ($check.is(":checked") == true) {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked == -1) {
                    //add id to selectedIds.
                    selectedIds.push($check.val());
                }
            }
            else {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked > -1) {
                    //remove id from selectedIds.
                    selectedIds = $.grep(selectedIds, function (item, index) {
                        return item != $check.val();
                    });
                }
            }
            updateMasterCheckbox();
        });
    });

    function onDataBound(e) {

        $('#customers-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
            var currentId = $(this).val();
            var checked = jQuery.inArray(currentId, selectedIds);
            //set checked based on if current checkbox's value is in selectedIds.
            $(this).attr('checked', checked > -1);
        });

        updateMasterCheckbox();
    }

    function updateMasterCheckbox() {
        var numChkBoxes = $('#customers-grid input[type=checkbox][id!=mastercheckbox]').length;
        var numChkBoxesChecked = $('#customers-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
        $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
    }

    function onDataBinding(e) {
        customerRoleIds = [];
        $('[name=SearchCustomerRoleIds]:checked').each(function () {
            customerRoleIds.push($(this).val());
        });
        getValuesFromControls();
        e.data = searchModel;
    }

    function getValuesFromControls() {
            searchModel = {
            SearchCustomerRoleIds: customerRoleIds.join(","),
            RegistrationFrom: $('#@Html.FieldIdFor(model => model.RegistrationFrom)').val(),
            RegistrationTo: $('#@Html.FieldIdFor(model => model.RegistrationTo)').val(),
            SearchEmail: $('#@Html.FieldIdFor(model => model.SearchEmail)').val(),
            SearchUsername: $('#@Html.FieldIdFor(model => model.SearchUsername)').val(),
            SearchFirstName: $('#@Html.FieldIdFor(model => model.SearchFirstName)').val(),
            SearchLastName: $('#@Html.FieldIdFor(model => model.SearchLastName)').val(),
            SearchDayOfBirth: $('#@Html.FieldIdFor(model => model.SearchDayOfBirth)').val(),
            SearchMonthOfBirth: $('#@Html.FieldIdFor(model => model.SearchMonthOfBirth)').val(),
            SearchCompany: $('#@Html.FieldIdFor(model => model.SearchCompany)').val(),
            SearchPhone: $('#@Html.FieldIdFor(model => model.SearchPhone)').val(),
            SearchCellPhone: $('#@Html.FieldIdFor(model => model.SearchCellPhone)').val(),
            SearchZipPostalCode: $('#@Html.FieldIdFor(model => model.SearchZipPostalCode)').val()
        };
    }
</script>
}